#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QPixmap>
#include <QMovie>
#include <QDebug>
#include <QFileInfo>
#include <QDir>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent), ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    index = 0;

    timer = new QTimer(this);
    timer->setInterval(1000);
    connect(timer, SIGNAL(timeout()), this, SLOT(func()));

    QDir imgPath("E:/Project/GEC6818/GZ2528/09-1103-QT/60-1107/test/QTimer");
    fileList = imgPath.entryList();

    for (auto it = fileList.begin(); it != fileList.end();)
    {
        if (QFileInfo(*it).suffix().toLower() != "png" && QFileInfo(*it).suffix().toLower() != "gif")
        {
            it = fileList.erase(it);
        }
        else
        {
            it++;
        }
    }

    for (auto a : fileList)
    {
        qDebug() << a;
    }

    // 标签显示图片  图片大小跟标签不匹配
    //     QPixmap map(":/img/aaa.png");
    //     ui->label->setPixmap(map);

    // 版本2 让图片跟标签大小适应
    //    QPixmap map(":/img/aaa.png");
    //    // 调整图片大小跟标签适应
    //    map.scaled(ui->label->width(),ui->label->height());
    //    // 让配置生效
    //    ui->label->setScaledContents(true);
    //    ui->label->setPixmap(map);

    // 标签显示动图
    QMovie *movie = new QMovie(":/img/cxk.gif");
    movie->start();
    movie->setScaledSize(ui->label->size());
    ui->label->setMovie(movie);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::func()
{

    if (fileList.length() == 0)
    {
        QMovie *movie = new QMovie(":/img/cxk.gif");
        movie->start();
        movie->setScaledSize(ui->label->size());
        ui->label->setMovie(movie);
        return;
    }

    QFileInfo info("E:/Project/GEC6818/GZ2528/09-1103-QT/60-1107/test/QTimer/" + fileList[index]);

    if (info.suffix() == "gif")
    {
        QMovie *movie = new QMovie(info.filePath());
        movie->start();
        movie->setScaledSize(ui->label->size());
        ui->label->setMovie(movie);
    }
    else
    {
        QPixmap map(info.filePath());
        // 调整图片大小跟标签适应
        map.scaled(ui->label->width(), ui->label->height());
        // 让配置生效
        ui->label->setScaledContents(true);
        ui->label->setPixmap(map);
    }

    index = (index + 1) % fileList.length();
}

void MainWindow::on_pushButton_clicked()
{
    timer->start();
}

void MainWindow::on_pushButton_2_clicked()
{
    timer->stop();
}
